*! version 0.0.2  19may2017  Michael Stepner, stepner@mit.edu
program define yamlout

	syntax using, [key(string) VALue(string) comment(string) fmt(string) replace]
	
	* Check for valid combination of key, value, comment
	if (`"`key'`value'`comment'"'=="") {
		di as error "key(), value() and comment() cannot all be blank"
		exit 198
	}
	if ("`value'"!="") & ("`key'"=="") {
		di as error "must specify key() if specified value()"
		exit 198
	}
	
	* Format value
	if (real("`value'")!=.) | ("`value'"==".") {  // numeric value
		if ("`fmt'"!="") local value=string(`value',"`fmt'")
		else local value=string(`value')
	}
	else {  // string value
		if ("`fmt'"!="") {
			di as error "can only specify fmt() for numeric value"
			exit 198
		}
	}
	
	* Replace or Append?
	if ("`replace'"=="replace") local overwrite replace
	else local overwrite append
	
	* Open file
	tempname file
	file open `file' `using', write text `overwrite'
	
	* Write YAML line
	if (`"`value'`key'"'=="") file write `file' `"# `comment'"' _n
	else if (`"`comment'"'=="") file write `file' `"`key': '`value''"' _n
	else file write `file' `"`key': '`value''  # `comment'"' _n
	
	* Close file
	file close `file'

end
